package vn.buffalocoders.rikos.ui.mylibrary;

import java.util.ArrayList;

import vn.buffalocoders.rikos.R;
import vn.buffalocoders.rikos.ui.category.BookCover;
import vn.buffalocoders.rikos.ui.common.RikoBook;
import vn.buffalocoders.rikos.ui.common.sessions.SessionManager;
import vn.buffalocoders.rikos.ui.network.ConnectRikoServer;
import vn.buffalocoders.rikos.ui.network.DownloadImageTask;
import android.R.bool;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class BookAdapter  extends BaseAdapter implements OnClickListener{
	private Context context;
    private ArrayList<RikoBook> listbook;
    private View gridView;
    private SessionManager session;
    public RikoBook BookFocus;
    public boolean bRePaint = false;
    public boolean bRePaintDone = true;
    public int PositionDel = -1;
    public BaseAdapter GridBookAdapter;
    private ProgressDialog progress;
	
    public BookAdapter(Context context ,ArrayList<RikoBook> listbook) {
	    this.context = context;
	    this.listbook = listbook;
	    session = new SessionManager(context);
	    GridBookAdapter = this;
	    progress = new ProgressDialog(context);
	}
   
    @Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
    	LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	final int fPosition =  position;
    	
    	 if (convertView == null || bRePaint) {	
    		gridView = new View(context);
 	        gridView = inflater.inflate(R.layout.my_book, null);
 	        final RikoBook book = listbook.get(position);

            //Set Image Book . Set Image Scale full
 	        BookCover img_book = (BookCover) gridView.findViewById(R.id.img_mybook);
 	        img_book.setOnClickListener(this);
 	        img_book.setNameBook(book.getTitle());
 	        new DownloadImageTask((ImageView) img_book)
                         .execute(String.format("%s%s", ConnectRikoServer.URL_IMAGE_HOME, book.getImageCover())); 	       
 	        img_book.setScaleType(ScaleType.FIT_XY); 	        
 	        ImageView img_delete_book= (ImageView) gridView.findViewById(R.id.img_mybook_close);
 	        img_delete_book.setOnClickListener( new OnClickListener() {
 	        	@Override
				   public void onClick(View v) { 
 	        			if(PositionDel == -1){	 	        			
	 	        			 PositionDel = fPosition;
	 						 DeleteBookMyLib deleteBookTask =  new DeleteBookMyLib();
	 						 deleteBookTask.execute(book.getId(), book.getNumber().toString());  	
 	        			}else{
 	        				Log.i("DBT_TEST", String.format("Waiting process delete", book.getId()));
 	        			}}});
    	 }
    	 else{
    		 gridView = (View) convertView;
	     }
	   
    	 return gridView;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listbook.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}
  	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.img_mybook) {
			BookCover view = (BookCover) v;
			//Toast.makeText(context,  "Book name " + view.getNameBook(), Toast.LENGTH_LONG).show();
		   //	Toast.makeText(context,  "IMAGE", Toast.LENGTH_LONG).show();
	    	// Intent intent = new Intent(context, SignUpActivity.class);
	    	// startActivity(intent);
			return;
		}
		
	}

	private void showProgress() {
		progress.setMessage(String.format("%s.......", context.getResources().getString(R.string.status_login)));
	    progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    progress.setIndeterminate(true);
	    progress.show();
	}
	
	private void hideProcess(){
		progress.hide();
	}
	
	public class DeleteBookMyLib extends AsyncTask<Object /* param */, Void /* Progress */, Integer /* Result */> {

		@Override
		protected Integer doInBackground(Object... params) {
			// TODO Auto-generated method stub			
			Log.i("DBT_TEST", String.format("DeleteBookMyLibTask authToken=%s,userID=%s, bookid=%s, number=%s", 
					session.getAuthToken(), session.getUserId(), (String)params[0], (String)params[1]));				
			return ConnectRikoServer.deleteBookMyLibrary(session.getAuthToken(), session.getUserId(), 
						 (String)params[0], (String)params[1]);

		}

		@Override
		protected void onPostExecute(Integer result) {
			if(result == 1){
				Toast.makeText(context,  "Delete Book Success", Toast.LENGTH_LONG).show();
				if(PositionDel != -1){					      				   
					listbook.remove(PositionDel);
					GridBookAdapter.notifyDataSetChanged();
	        		bRePaint = true;
					PositionDel = -1;
				}
				
			}				
			else{				
				Toast.makeText(context,  "Delete Book Failed" , Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected void onCancelled() {
			
		}
	}
}
